using System;
using System.Collections;
using System.Collections.Generic;
using PEMath;
using UnityEngine;

/****************************************************
// 功能：主要逻辑单位 属性状态处理
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/28 16:31:15
*****************************************************/

public partial class MainLogicUnit
{

    // 血量回调
    public Action<int, JumpUpdateInfo> OnHpChange;

    // 收到伤害回调
    public Action OnHurt;

    // 死亡回调
    public Action<MainLogicUnit> OnDeath;
    
    /// <summary>
    /// 状态改变回调
    /// </summary>
    public Action<StateEnum, bool> OnStateChange;
    
    /// <summary>
    /// 被减速时
    /// </summary>
    public Action<JumpUpdateInfo> OnSlowDown;
    
    #region 属性状态数据

    public PEInt Hp { private set; get; }

    public PEInt Def { private set; get; }

    public PEInt AttackSpeedRateBase;
    private PEInt attackSpeedRate;
    public PEInt AttackSpeedRate {
        private set {
            attackSpeedRate = value;
            var skill = GetNormalSkill();
            if (skill == null) return;
            skill.skillTime = skill.config.skillTime * AttackSpeedRateBase / attackSpeedRate;
            skill.spellTime = skill.config.spellTime * AttackSpeedRateBase / attackSpeedRate;
        }
        get => attackSpeedRate;
    }
    
    // 击飞计数：无法移动，无法施放技能（包括普攻）,无法被水银净化解控
    private int knockupCount;
    public int KnockupCount {
        get => knockupCount;
        set {
            knockupCount = value;
            if(IsKnockup()) {
                InputFakeMoveKey(PEVector3.zero);
                OnStateChange?.Invoke(StateEnum.Knockup, true);
                LogicPos += new PEVector3(0, (PEInt)0.5F, 0);
            }
            else {
                OnStateChange?.Invoke(StateEnum.Knockup, false);
                LogicPos += new PEVector3(0, (PEInt)(-0.5F), 0);
            }
        }
    }
    private bool IsKnockup() {
        return knockupCount != 0;
    }
    // 沉默计数：沉默时无法施放技能
    private int silenceCount;
    public int SilenceCount {
        get => silenceCount;
        set
        {
            silenceCount = value;
            OnStateChange?.Invoke(StateEnum.Silenced, IsSilenced());
        }
    }
    public bool IsSilenced() {
        return silenceCount != 0;
    }
    // 晕眩计数：无法移动，无法施放技能（包括普攻），可以被水银净化解控
    int stunnedCount;
    public int StunnedCount {
        get => stunnedCount;
        set {
            stunnedCount = value;
            if(IsStunned()) {
                InputFakeMoveKey(PEVector3.zero);
                OnStateChange?.Invoke(StateEnum.Stunned, true);
                //Debug.Log("stun start");
            }
            else {
                OnStateChange?.Invoke(StateEnum.Stunned, false);
                //Debug.Log("stun end");
            }
        }
    }
    public bool IsStunned() {
        return stunnedCount != 0;
    }
    #endregion
    
    public void InitProperties()
    {
        Hp = unitData.unitConfig.hp;
        Def = unitData.unitConfig.def;
    }

    public void InitAttackSpeedRate(PEInt rate)
    {
        AttackSpeedRateBase = rate;
        // 每秒钟进行多少次攻击
        AttackSpeedRate = rate;
    }

    public bool IsTeam(TeamEnum teamEnum)
    {
        return unitData.teamEnum == teamEnum;
    }
    
    public void ResetHP() {
        Hp = unitData.unitConfig.hp;
        OnHpChange?.Invoke(Hp.RawInt, null);
    }

    #region  API Functions

    public void GetDamageBySkill(PEInt damage, Skill skill)
    {
        // 比如挂载Arthur标记buff，此时受伤会有额外伤害
        OnHurt?.Invoke();
        PEInt hurt = damage - Def;
        if (hurt > 0)
        {
            Hp -= hurt;
            if (Hp <= 0)
            {
                Hp = 0;
                unitState = UnitStateEnum.Dead;
                InputFakeMoveKey(PEVector3.zero);
                OnDeath?.Invoke(skill.owner);
                PlayAni("death");
                Debug.Log($"{unitName} hp=0, Dead");
            }
            //Debug.Log($"{unitName} hp = {Hp.RawInt}");

            JumpUpdateInfo jump = null;
            if (IsPlaySelf() || skill.owner.IsPlaySelf())
            {
                jump = new JumpUpdateInfo()
                {
                    jumpVal = hurt.RawInt,
                    jumpType = JumpTypeEnum.SkillDamage,
                    jumpAni = JumpAniEnum.LeftCurve
                };
            }
            OnHpChange?.Invoke(Hp.RawInt, jump);
        }
    }

    public void GetDamageByBuff(PEInt damage, Buff buff, bool calcCB = true) {
        if(calcCB) {
            OnHurt?.Invoke();
        }
        if(buff.cfg.hitTickAudio != null) {
            PlayAudio(buff.cfg.hitTickAudio);
        }

        PEInt hurt = damage - Def;
        if(hurt > 0) {
            Hp -= hurt;
            if(Hp <= 0) {
                Hp = 0;
                unitState = UnitStateEnum.Dead;//状态切换
                InputFakeMoveKey(PEVector3.zero);
                OnDeath?.Invoke(buff.source);
                PlayAni("death");
            }

            JumpUpdateInfo jui = null;
            if(IsPlaySelf() || buff.source.IsPlaySelf() || buff.owner.IsPlaySelf()) {
                jui = new JumpUpdateInfo {
                    jumpVal = hurt.RawInt,
                    jumpType = JumpTypeEnum.BuffDamage,
                    jumpAni = JumpAniEnum.RightCurve
                };
            }
            OnHpChange?.Invoke(Hp.RawInt, jui);
        }
    }
    
    public void GetCureByBuff(PEInt cure, Buff buff) {
        if(Hp >= unitData.unitConfig.hp) {
            //Debug.Log("血量已经恢复，治疗溢出");
            return;
        }
        Hp += cure;
        PEInt trueCure = cure;
        if(Hp > unitData.unitConfig.hp) {
            trueCure -= (Hp - unitData.unitConfig.hp);
            Hp = unitData.unitConfig.hp;
        }

        JumpUpdateInfo jui = null;
        //作用目标是英雄角色自己
        //buff来源是英雄自己
        //buff附着目标是英雄角色自己
        if(IsPlaySelf() || buff.source.IsPlaySelf() || buff.owner.IsPlaySelf()) {
            jui = new JumpUpdateInfo {
                jumpVal = trueCure.RawInt,
                jumpType = JumpTypeEnum.Cure,
                jumpAni = JumpAniEnum.CenterUp
            };
        }
        OnHpChange?.Invoke(Hp.RawInt, jui);
    }
    
    public void ModifyMoveSpeed(PEInt value, Buff buff, bool jumpInfo) {
        //Debug.Log("移速Offset ScaleValue:" + value.ScaledValue);
        LogicMoveSpeed += value;
        //Debug.Log("MoveSpeed:" + LogicMoveSpeed.ScaledValue);
        if (value >= 0 || !jumpInfo) return;
        // 减速跳字
        JumpUpdateInfo jui = null;
        if(IsPlaySelf()) {
            jui = new JumpUpdateInfo {
                jumpType = JumpTypeEnum.SlowSpeed,
                jumpAni = JumpAniEnum.CenterUp
            };
        }
        OnSlowDown?.Invoke(jui);
    }
    public void ModifyAttackSpeed(PEInt value) {
        AttackSpeedRate += value;
    }

    #endregion
    
}
